package com.tedu.weibo.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tedu.weibo.common.result.JsonResult;
import com.tedu.weibo.common.result.StatusCode;
import com.tedu.weibo.mapper.WeiboMapper;
import com.tedu.weibo.pojo.dto.WeiboDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.entity.Weibo;
import com.tedu.weibo.pojo.vo.WeiboDetailVO;
import com.tedu.weibo.pojo.vo.WeiboVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Api(tags = "微博模块")
@RestController
@RequestMapping("/v1/weibo")
@Slf4j
@Validated
public class WeiboController {

    @Autowired
    private RedisTemplate<String , Serializable> redisTemplate;
    @Autowired
    private WeiboMapper weiboMapper;

    // 发布微博
    @ApiOperation("发表微博功能")
    @PostMapping("/insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        log.info("WeiboController.insert() ,发表微博"); // 记录执行模块
        log.trace("开始执行insert 方法"); // 记录程序运行轨迹的
        log.debug("weiboDTO={}", weiboDTO); // 记录程序处理结果，辅助判断逻辑

        User user = (User) session.getAttribute("user");
        log.trace("通过session获取用户的登录信息");
        log.debug("user={}", user); // 不建议用toString 可能会空指针

        if (user == null) { // 未登录
            log.trace("user为null，未登录");
            return new JsonResult(StatusCode.NOT_LOGIN);
        } else {
            log.trace("user不为null，已登录,处理发表微博");

            // 插入微博
            Weibo weibo = new Weibo();
            BeanUtils.copyProperties(weiboDTO, weibo);
            weibo.setUserId(user.getId());
            weibo.setCreated(new Date());

            log.debug("weibo={}", weibo); // 记录程序处理结果，辅助判断逻辑

            weiboMapper.insert(weibo);
            log.trace("插入微博完毕");

            log.info("微博发布成功"); // 记录操作结果
            return JsonResult.success();
        }
    }

    // 查询所有微博
    @ApiOperation("查询所有微博")
    @GetMapping("/selectIndex")
    public JsonResult selectIndex() throws JsonProcessingException {
        String weiboListStr = (String) redisTemplate.opsForValue().get("weiboList");
        if (weiboListStr == null) {
            List<WeiboVO> list = weiboMapper.selectAll();
            // jackson 提供一个API 可以将任意对象转换成json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonString = objectMapper.writeValueAsString(list);
            redisTemplate.opsForValue().set("weiboList", jsonString);
            return JsonResult.success(list);
        }else {
            // 将json字符串转换成对象
            ObjectMapper objectMapper = new ObjectMapper();
            // 利用 objectMapper 将json字符串转换成对象
            List<WeiboVO> list= objectMapper.readValue(weiboListStr, List.class);
            return JsonResult.success(list);
        }

    }

    // 查询具体微博
    @ApiOperation("查询微博详情")
    @GetMapping("/selectById")
    @ApiImplicitParam(name = "id",value = "微博id",required = true,dataType = "int",example = "1")
    public JsonResult selectById(@Range(min = 1,max = Integer.MAX_VALUE,message = "微博id范围有误") int id){

        WeiboDetailVO weiboDetailVO=weiboMapper.selectById(id);
        return JsonResult.success(weiboDetailVO);
    }

    @GetMapping("/selectByIdAndName")
    @ApiOperation(value = "根据微博id和用户昵称查询微博详情,演示多参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "微博id",required = true,dataType = "int",example = "1"),
            @ApiImplicitParam(name = "nickname",value = "用户昵称",required = true,dataType = "String",example = "昵称")
    })
    public WeiboDetailVO selectWeiboByIdAndName(int id,String nickname){
        //return weiboMapper.selectWeiboByIdAndName(id,nickname);
        return weiboMapper.selectById(id);
    }



    // 删除微博  状态码 0 删除失败 1 删除成功 2 未登录 3 没有权限
    @ApiOperation("删除微博功能")
    @DeleteMapping("/delectWeibo/{id}")
    @ApiImplicitParam(name = "id",value = "微博id",required = true,dataType = "int",example = "1")
    public int delectWeibo(@PathVariable Integer id,@ApiIgnore HttpSession session){
        log.info("delectWeibo 删除微博");
        User user=(User) session.getAttribute("user");
        log.debug("当前用户的信息user:"+user);
        if (user==null){
            return 2;
        }
        // 判断是否是本人 操作
        Weibo weibo=weiboMapper.selectWeiboById(id);
        // 测试输出
//        System.out.println("weibo="+weibo);
//        System.out.println("user="+user);
        if (weibo.getUserId()!=user.getId()){
            return 3;
        }
        int num= weiboMapper.deleteById(id);
        return num>0?1:0;
    }


}
